import Taro from "@tarojs/taro"
import {appId, baseUrl} from "../config"

const login = async () => {
  const {code} = await Taro.login()
  const res = await Taro.request({
    url: `${baseUrl}/wx/auth/${appId}/user/login?code=${code}`,
    method: 'GET'
  })
  const json = res.data
  const {success, data} = json
  if (success) {
    const {customer} = data
    Taro.setStorageSync('sessionKey', data.sessionKey)
    Taro.setStorageSync('customerId', customer.id)
    Taro.setStorageSync('userInfo', customer)
    return true
  }else {
    console.log('获取用户信息失败，也就是登录失败了')
    return false
  }
}

const request = async ({url, json, method}) => {
  const res = await Taro.request({
    url: baseUrl + url,
    header: {
      'session-key': Taro.getStorageSync('sessionKey'),
    },
    data: json,
    method
  })
  const {statusCode, errMsg, data}=res
  // console.log(res)
  if (statusCode === 200) {
    const {code, success} = data
    if (!success) {
      if (code === '300001') {
        const bol = await login()
        if(bol) {
          return request({url, json, method})
        }
      }
    }
  }else {
    console.log(`网络错误：${errMsg}`)
  }
  // console.log(data)
  return data
}

export const get = (url, data) => {
  return request({
    url,
    data,
    method: 'GET'
  })
}

export const post = (url, data) => {
  return request({
    url,
    data,
    method: 'POST'
  })
}
